// 引入接口文件
import {
  getDetail,
  update,
  create,
  labelQueryList,
  areAddressGet,
  houseListGet,
  gethouseTypeList,
  queryAccount,
} from './commodityEditServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
/*isEmpty 对象是否为空
 *isArray 对象是否数组
 *cloneDeep 对象深拷贝
 */
import { isEmpty, isArray, cloneDeep, merge, pick } from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
import AppBus from '../../../../utils/bus'
let productTypeLabelMap = { 1: '详细房号', 2: '车位位置', 3: '商铺位置', }
// 初始默认状态
const defultState = {
  xxx: '1',
  loading: false,
  btnLoading: false,
  id: '',
  parentProductId: '',
  pageType: '',
  sellType: '1',
  isClone: false,
  checked: false,
  accountList: [],//根据项目查找对公账户
  allAddress: [],
  houseList: [],
  detailInfo: {},
  formData: {
    'parentProductId': '',//项目id
    'parentProductName': '',//项目名称
    'detail': '',
    'productId': '',
    'catalogId':'',//商品类型
    'description':'',//商品介绍
     'price':'',//参考价格
    'medias':[
     
    ],
    'name':'',//商品名称
    
  },
  standards:{
    volume:'',
    weight:'',
    power:'',
    size:'',
    color:'',
    producingArea:'',
    other:''
  },
  selectOption: {
    value: '', // 选择的默认1
    des: '', // 选择的默认
  },

  teamsOptions:[
    {value:'volume', label:'容量'},
    {value:'weight', label:'重量'},
    {value:'power', label:'功率'},
    {value:'size', label:'体积'},
    {value:'color', label:'颜色'},
    {value:'producingArea', label:'产地'},
    {value:'other', label:'其他'},
  ],
  medias:[
    
  ],
  houseTypeList: [],//户型列表
  modalObj: {
    project: {
    visible: false,
    },
    productList: {
      visible: false,
    },
  },
  productId:'',
  areaList1:[],
  biz:{
    queryForm:{
      province: null,
      city:null,
      pageSize: 10,
      pageNo:1,
      name:null
    },
    selectedRowKeys:[]
  },
}

// 声明module
const tmpModule = {
  // namespace: 'secondKillingSetting',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        if ('' + tmpModule.pathname === '' + pathname) {
          dispatch({ type: 'updateStore', payload: { ...cloneDeep(defultState), ...query } })//每次进去页面先重置状态
          console.log('subscriptions', pathname, query)
          if (query.pageType == 'edit' || query.pageType == 'detail') {
            dispatch({
              type: 'updateStore',
              payload: {
                pageType: query.pageType,
                id: query.id,
                isClone: query.isClone||false,
              }
            })
            dispatch({
              type:'getDetail',
              payload:{
                productId:query.id
              }
            })
          } else {
            dispatch({
              type: 'updateStore',
              payload: {
                pageType: query.pageType,
                id: query.id,
                isClone: query.isClone||false,
              }
            })
          }
          dispatch({ type: 'gethouseTypeList', payload: {} })
          dispatch({ type: 'getArea', payload: {} })
        } // end if
      }) // end listen
    },
  },

  // 方法列表
  effects: {
    // 查询记录  详情
    // 获取区域地址
    *getArea({ payload }, { put, call, select }) {
      try {
        const { success, data } = yield call(areAddressGet)
        if (success) {
          //todo: 接口格式调整后删除
          let arr = [data[0]]
          data[0] = {
            label: '北京',
            value: '110100',
            children: arr
          }
          //去掉第三级，
          for (var i = 0; i < 33; i++) {
            for (var j = 0; j < data[i].children.length; j++) {
              delete data[i].children[j].children
            }
          }
          yield put({ type: 'updateStore', payload: { allAddress: data } })
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 获取户型项目
    *houseListGet({ payload }, { put, call, select }) {
      try {
        const { success, rows } = yield call(houseListGet, { ...payload, pageSize: 10000 })
        if (success) {
          let list=rows||[]
          let arr=[]
          list.map((item,index)=>{
            arr.push({ label: item.name||'', value: item.productId+''||'' })
          })
          yield put({ type: 'updateStore', payload: { houseList: arr || [] } })
        }
      } catch (e) {
        console.log(e)
      }
    },

    *gethouseTypeList({ payload }, { put, call, select }) {
      try {
        let params = {
          pageNo: 1,
          pageSize: 1000,
          ...payload
        }
        const { success, msg, rows } = yield call(gethouseTypeList, { ...params })
        let list = []
        yield put({ type: 'updateStore', payload: { houseTypeList: rows || [] } })

      } catch (e) {
      }
    },
    //获取详情

    // 修改
    *update({ payload }, { put, select, call }) {
      let { id, formData, medias,selectOption,standards,teamsOptions} = yield select(state => state[tmpModule.namespace])
      // 转译成接口需要的
      for(let i in standards){
        if(selectOption.value==i){
          standards[i]=selectOption.des
        }else{
          delete standards[i]
        }
      }
      // let key = ''
      // switch(selectOption.value+''){
      //   case '1':// 容量
      //     formData.volume = selectOption.des
      //     key='volume'
      //     break;
      //   case '2':// 重量
      //     formData.weight = selectOption.des
      //     key='weight'
      //     break;
      //   case '3':// 功率
      //     formData.power = selectOption.des
      //     key='power'
      //     break;
      //   case '4':// 体积
      //     formData.size = selectOption.des
      //     key='size'
      //     break;
      //   case '5':// 颜色
      //     formData.color = selectOption.des
      //     key='color'
      //     break;
      //   case '6':// 产地
      //     formData.producingArea = selectOption.des
      //     key='producingArea'
      //     break;
      //   case '7':// 其他
      //     formData.other = selectOption.des
      //     key='other'
      //     break;
      // }
      let params = {
        productId: id,
        ...pick(formData, [ 'medias', 'parentProductId','parentProductName','catalogId','name','price','description']),
        medias,
        ...standards,
      }

      // 商品类型非房源，不用传户型和户型朝向
      const { success, msg, data } = yield call(update, { ...params })
      if (success) {
        message.success('操作成功', 1, () => {
          // yield put({type: 'queryInfo', payload: {}})
          let urlArray = MODULE_TO_ROUTES[tmpModule.namespace].urlArray
          console.log('urlArray', urlArray)
          AppBus.emit('closeTab', {
            key: urlArray[0],
            cbf: () => {
              hashHistory.push(urlArray[1])
              payload.resetFields()
            }
          })
        })
      }
    },
    // 新增
    *create({ payload }, { put, select, call }) {
      let { id, formData, tags, medias , selectOption,standards} = yield select(state => state[tmpModule.namespace])
      // 转译成接口需要的
      // let key = ''
      // switch(selectOption.value+''){
      //   case '1':// 容量
      //     formData.volume = selectOption.des
      //     key='volume'
      //     break;
      //   case '2':// 重量
      //     formData.weight = selectOption.des
      //     key='weight'
      //     break;
      //   case '3':// 功率
      //     formData.power = selectOption.des
      //     key='power'
      //     break;
      //   case '4':// 体积
      //     formData.size = selectOption.des
      //     key='size'
      //     break;
      //   case '5':// 颜色
      //     formData.color = selectOption.des
      //     key='color'
      //     break;
      //   case '6':// 产地
      //     formData.producingArea = selectOption.des
      //     key='producingArea'
      //     break;
      //   case '7':// 其他
      //     formData.other = selectOption.des
      //     key='other'
      //     break;

      // }
      for(let i in standards){
        if(selectOption.value==i){
          standards[i]=selectOption.des
        }else{
          delete standards[i]
        }
      }
      if(medias.length<1){
        medias=[{fileUrl: '',busiType:'seckill',fileType:'1'}]
      }
      let params = {
        ...pick(formData, ['description','price', 'medias','productId', 'parentProductId','parentProductName','catalogId','name',]),
        medias,
        ...standards,
      }
      const { success, msg, data } = yield call(create, { ...params })
      if (success) {
        message.success('操作成功', 1, () => {
          // yield put({type: 'queryInfo', payload: {}})
          let urlArray = MODULE_TO_ROUTES[tmpModule.namespace].urlArray
          console.log('urlArray', urlArray)
          AppBus.emit('closeTab', {
            key: urlArray[0],
            cbf: () => {
              hashHistory.push(urlArray[1])
              payload.resetFields()
            }
          })
        })
      }
    },
    *getDetail({payload},{put,call,select}){
      let {selectOption,teamsOptions,biz} = yield select(state => state[tmpModule.namespace])
     try{
      let {data,success}=yield call(getDetail,payload)
      if(success){
        console.log(data)
        for(let x in teamsOptions){
          for(let y in data){
            if(teamsOptions[x].value==y){
              console.log(y,data[y])
              selectOption.value=y
              selectOption.des=data[y]
            }
          }
        }
        biz.queryForm={
          ...biz.queryForm,
          province:data.province,
          city:data.city,
          name:data.parentProductName
        } 
        biz.selectedRowKeys[0]=data.parentProductId
          yield put({
            type:'updateStore',
            payload:{
              formData:data,
              medias:data.medias || [],
              selectOption,
              biz,
            }
          })
      }
     }catch(err){

     }
      
    }
  },
  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
